<?php

// Namespace

namespace Snsfg;


/**
 * CMedia is a class that can be used to upload and download medias to/from WeChat
 *
 * @package		Snsfg
 * @category	Model
 */

class CMedia extends \Loop\CObject
{
	
	protected function createProperties()
	{
		
		parent::createProperties();

		$this->createProperty
		(
			'name',
			array
			(
				'type' => TYPE_STRING_LONG
			)
		);

		$this->createProperty
		(
			'pathTo',
			array
			(
				'type' => TYPE_STRING_LONG
			)
		);

		$this->createProperty
		(
			'sourceUrl',
			array
			(
				'type' => TYPE_STRING_LONG
			)
		);

		$this->createProperty
		(
			'type',
			array
			(
				'type' => TYPE_STRING_SHORT
			)
		);

		$this->createProperty
		(
			'mediaId',
			array
			(
				'type' => TYPE_STRING_LONG
			)
		);

		$this->createProperty
        (
            'createTime',
            array
            (
                'type' => TYPE_TIMESTAMP
            )
        );
	}


	/**
	 *
	 * @param $url       string      远程文件地址
	 * @param $filename  string      保存后的文件名（为空时则为随机生成的文件名，否则为原文件名）
	 * @param $fileType  array       允许的文件类型
	 * @param $dirName   string      文件保存的路径（路径其余部分根据时间系统自动生成）
	 * @param $type      int         远程获取文件的方式
	 * @return           json        返回文件名、文件的保存路径
	 * 
	 */

	public function api_getImage()
	{
		echo $this->downloadImage('http://img.wan.renren.com/images/2013/0430/1367294093164.jpg', '', pref('[Snsfg]/pathToWechatMedia'), pref('[Snsfg]/WechatMedia/Image'));
	}

	
	function downloadImage($url, $filename='', $dirName, $fileType, $type=0)
	{
		if($url == ''){return false;}

		
		// Get original name
		
		$defaultFileName = basename($url);
		

		// Get file type
		
		$suffix = substr(strrchr($url,'.'), 1);
		
		if(!in_array($suffix, $fileType)){
			return false;
		}
		

		// Set file name
		
		$filename = $filename == '' ? time().rand(0,9).'.'.$suffix : $defaultFileName;

		
		// Get resource
		
		if($type){
			$ch = curl_init();
			$timeout = 5;
			curl_setopt($ch, CURLOPT_URL, $url);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
			$file = curl_exec($ch);
			curl_close($ch);
		}else{
			ob_start();
			readfile($url);
			$file = ob_get_contents();
			ob_end_clean();
		}
		

		// Path to save image
		
		// $dirName = $dirName.'/'.date('Y', time()).'/'.date('m', time()).'/'.date('d',time()).'/';
		$dirName = $dirName.'/'.date('Y', time()).'/'.date('m', time()).'/';
		
		if(!file_exists($dirName)){
			mkdir($dirName, 0777, true);
		}
		

		// Save image
		
		$res = fopen($dirName.$filename,'a');
		
		fwrite($res,$file);
		fclose($res);


		$result = array(
					'name' => $filename,
					'pathTo' => $dirName
				);
		
		//return "{'fileName':$filename, 'saveDir':$dirName}";
		return $result;
	}
}